<template>
  <div class="profile-page-container">
    <transition name="el-zoom-in-top">
      <div v-if="showContent" class="profile-container">
        <el-card v-if="!authStore.isAuthenticated" class="profile-box">
          <el-empty description="请先登录以查看您的个人中心" />
        </el-card>

        <el-card v-else class="profile-box">
          <template #header>
            <div class="card-header">
              <span><el-icon><User /></el-icon> 个人中心</span>
              <el-button type="primary" :icon="CollectionTag" @click="toFavorite">我的收藏</el-button>
            </div>
          </template>

          <el-descriptions :column="1" border>
            <el-descriptions-item>
              <template #label><div class="description-label"><el-icon><Avatar /></el-icon> 用户名</div></template>
              {{ authStore.user.username }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label><div class="description-label"><el-icon><Postcard /></el-icon> 角色</div></template>
              <el-tag :type="authStore.user.role === 'public' ? '' : 'success'">
                {{ authStore.user.role === 'public' ? '公众用户' : '管理员' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item v-if="authStore.user.role === 'public'">
              <template #label><div class="description-label"><el-icon><Key /></el-icon> API Key</div></template>
              <div class="api-key-content">
                <span v-if="apiKeyLoading">正在加载...</span>
                <span v-else-if="authStore.apikey" class="api-key-text">{{ authStore.apikey }}</span>
                <span v-else>未能获取 API Key，请稍后再试或联系支持。</span>
                <div class="api-key-actions">
                  <el-button
                    type="primary"
                    link
                    @click="fetchUserApiKey"
                    :loading="apiKeyLoading"
                    :icon="Refresh"
                  >
                    {{ authStore.apikey ? '刷新' : '获取' }}
                  </el-button>
                  <el-button
                    v-if="authStore.apikey"
                    type="primary"
                    link
                    @click="handleCopyApiKey"
                    :icon="CopyDocument"
                  >
                    复制
                  </el-button>
                </div>
              </div>
            </el-descriptions-item>
          </el-descriptions>

          <template v-if="authStore.user.role === 'public'">
            <el-divider content-position="left"><div class="divider-content"><el-icon><EditPen /></el-icon> 修改用户名</div></el-divider>
            <div class="form-section">
              <el-form :model="usernameForm" ref="usernameFormRef" label-position="top" @submit.prevent="handleChangeUsername">
                <el-form-item
                  label="新用户名"
                  prop="new_username"
                  :rules="[
                    { required: true, message: '请输入新用户名', trigger: 'blur' },
                    { min: 3, max: 50, message: '用户名长度应为3到50个字符', trigger: 'blur' }
                  ]"
                >
                  <el-input v-model.trim="usernameForm.new_username" placeholder="请输入新的用户名" :prefix-icon="User" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" native-type="submit" :loading="usernameChangeLoading" :icon="Select">确认修改</el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-divider content-position="left"><div class="divider-content"><el-icon><Lock /></el-icon> 修改密码</div></el-divider>
            <div class="form-section">
              <el-form :model="passwordForm" ref="passwordFormRef" label-position="top" @submit.prevent="handleChangePassword">
                <el-form-item label="当前密码" prop="old_password" :rules="[{ required: true, message: '请输入当前密码', trigger: 'blur' }]">
                  <el-input type="password" v-model="passwordForm.old_password" show-password placeholder="请输入当前所用密码" :prefix-icon="Unlock" />
                </el-form-item>
                <el-form-item label="新密码" prop="password" :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]">
                  <el-input type="password" v-model="passwordForm.password" show-password placeholder="请输入新的安全密码" :prefix-icon="Lock" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" native-type="submit" :loading="passwordChangeLoading" :icon="Select">确认修改</el-button>
                </el-form-item>
              </el-form>
            </div>
          </template>
        </el-card>
      </div>
    </transition>
  </div>

  <div class="fab-button">
    <el-tooltip content="返回地图" placement="left">
      <el-button type="primary" circle :icon="Back" @click="handleExit" />
    </el-tooltip>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import { useRouter } from "vue-router";
import {
  User,
  Key,
  CollectionTag,
  EditPen,
  Lock,
  Refresh,
  CopyDocument,
  Avatar,
  Postcard,
  Select,
  Back,
  Unlock
} from '@element-plus/icons-vue';

const router = useRouter();
const authStore = useAuthStore();
const userStore = useUserStore();

// 控制内容显示，用于实现动画
const showContent = ref(false);

const apiKeyLoading = ref(false);

// --- 修改用户名相关 ---
const usernameFormRef = ref(null);
const usernameForm = ref({ new_username: '' });
const usernameChangeLoading = ref(false);

// --- 修改密码相关 ---
const passwordChangeLoading = ref(false);
const passwordFormRef = ref(null);
const passwordForm = ref({ old_password: '', password: '' });

// 获取API Key
const fetchUserApiKey = async () => {
  apiKeyLoading.value = true;
  await authStore.fetchApiKey();
  apiKeyLoading.value = false;
  if (!authStore.apikey) {
    ElMessage.warning('未能获取到 API Key，可能是您刚注册或网络问题。');
  }
};

// 新增：复制API Key
const handleCopyApiKey = () => {
  if (!authStore.apikey) return;
  navigator.clipboard.writeText(authStore.apikey).then(() => {
    ElMessage.success('API Key 已成功复制到剪贴板！');
  }).catch(err => {
    console.error('Copy API Key error:', err);
    ElMessage.error('复制失败，您的浏览器可能不支持此功能。');
  });
};

// --- 修改用户名逻辑 ---
const handleChangeUsername = async () => {
  if (!usernameFormRef.value) return;
  await usernameFormRef.value.validate(async (valid) => {
    if (valid) {
      if (usernameForm.value.new_username === authStore.user.username) {
        ElMessage.info('新用户名与当前用户名相同，无需修改。');
        return;
      }
      usernameChangeLoading.value = true;
      try {
        const success = await userStore.updateCurrentUser({
          username: usernameForm.value.new_username
        });
        if (success) {
          ElMessage.success('用户名修改成功！');
          await authStore.checkAuthStatus(true);
          usernameForm.value.new_username = '';
          usernameFormRef.value.resetFields();
        }
      } finally {
        usernameChangeLoading.value = false;
      }
    } else {
      ElMessage.error('请检查您输入的内容是否符合要求');
      return false;
    }
  });
};

// --- 修改密码逻辑 ---
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return;
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordChangeLoading.value = true;
      try {
        const success = await userStore.updateCurrentUser({
          old_password: passwordForm.value.old_password,
          password: passwordForm.value.password
        });
        if (success) {
          ElMessage.success('密码修改成功！');
          passwordForm.value.old_password = '';
          passwordForm.value.password = '';
          passwordFormRef.value.resetFields();
        }
      } finally {
        passwordChangeLoading.value = false;
      }
    } else {
      ElMessage.error('请检查您输入的内容是否符合要求');
      return false;
    }
  });
};

// 路由跳转
const handleExit = async () => {
  await router.push('/map');
};
const toFavorite = async () => {
  await router.push('/profile/myfavorite');
};

// onMounted 生命周期钩子
onMounted(() => {
  // 触发进入动画
  showContent.value = true;

  // 如果已登录且是公众用户，但store中没有apikey，则自动获取
  if (authStore.isAuthenticated && authStore.user?.role === 'public' && !authStore.apikey) {
    fetchUserApiKey();
  }
});
</script>

<style scoped>
/* 页面容器，添加现代化背景色 */
.profile-page-container {
  display: flex;
  justify-content: center;
  align-items: flex-start; /* 从顶部开始对齐 */
  padding: 40px 20px;
  background-color: #f0f2f5; /* 柔和的背景色 */
  min-height: 100vh; /* 确保背景铺满整个视口 */
  box-sizing: border-box;
}

.profile-container {
  width: 100%;
}

/* 卡片样式，增加圆角和阴影动效 */
.profile-box {
  width: 100%;
  max-width: 800px; /* 适当增加宽度 */
  margin: 0 auto;
  border-radius: 12px; /* 更大的圆角 */
  border: none; /* 移除默认边框 */
  transition: box-shadow 0.3s ease-in-out, transform 0.3s ease-in-out;
}

.profile-box:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1); /* 悬停时更明显的阴影 */
  transform: translateY(-5px);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.1rem;
  font-weight: 600;
}
.card-header .el-icon {
  margin-right: 8px;
  vertical-align: middle;
}

/* 描述列表标签样式 */
.description-label {
  display: inline-flex;
  align-items: center;
  gap: 8px; /* 图标和文字的间距 */
}

/* API Key 内容区域样式 */
.api-key-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap; /* 换行以适应小屏幕 */
  gap: 10px;
}
.api-key-text {
  font-family: 'Courier New', Courier, monospace;
  background-color: #ecf5ff;
  padding: 2px 6px;
  border-radius: 4px;
  color: #409eff;
  word-break: break-all;
}

/* 分割线标题样式 */
.divider-content {
  display: inline-flex;
  align-items: center;
  font-size: 1rem;
  color: #333;
}
.divider-content .el-icon {
  margin-right: 8px;
}
.el-divider {
  margin: 30px 0; /* 增加分割线上下的间距 */
}

/* 表单区域统一样式 */
.form-section {
  padding: 0 10px; /* 左右留出一些内边距 */
  margin-top: 20px;
}

/* 输入框前缀图标样式 */
:deep(.el-input__prefix) {
  align-items: center;
}

/* 浮动操作按钮 (FAB) */
.fab-button {
  position: fixed;
  right: 40px;
  bottom: 40px;
  z-index: 100;
}
.fab-button .el-button {
  width: 55px;
  height: 55px;
  font-size: 24px; /* 图标大小 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); /* 添加阴影使其更突出 */
}
</style>